package com.chenyitun.cloudsystem.utils;


import com.chenyitun.cloudcommon.utils.SpringContextHolder;
import com.chenyitun.cloudsystem.dao.UserDao;
import com.chenyitun.cloudsystem.domain.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroUtils {
    @Autowired
    private static SessionDAO sessionDAO;

    private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);
    public static Subject getSubjct() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取当前用户
     * @return 取不到返回 new User()
     */
    public static User getUser(){
        try {
            Subject subject = SecurityUtils.getSubject();
            User user = (User) subject.getPrincipal();
            if (user != null) {
                return user;
            }
//			subject.logout();
        } catch (UnavailableSecurityManagerException e) {

        } catch (InvalidSessionException e) {

        }
        return new User();
    }

//    /**
//     * 获取当前登录者对象
//     */
//    public static Principal getPrincipal() {
//        try {
//            Subject subject = SecurityUtils.getSubject();
//            Object obj =  subject.getPrincipal();
//            Principal principal = null ;
//            if(obj instanceof Principal)
//                principal = (Principal) obj;
//            if (principal != null) {
//                return principal;
//            }
////			subject.logout();
//        } catch (UnavailableSecurityManagerException e) {
//
//        } catch (InvalidSessionException e) {
//
//        }
//        return null;
//    }

    public static Long getUserId() {
        return getUser().getUserId();
    }

    public static void logout() {
        getSubjct().logout();
    }


    public static Session getSession() {
        try {
            Subject subject = getSubjct();
            Session session = subject.getSession(false);
            if (session == null) {
                session = subject.getSession();
            }
            if (session != null) {
                return session;
            }
//			subject.logout();
        } catch (InvalidSessionException e) {

        }
        return null;
    }

}

